#include "broadcastkey.h"
#include <QNetworkAddressEntry>
#include <QCoreApplication>
#include <QFile>
static const qint32 BROADCASTINTERVAL = 6000; // increase time
static const unsigned BROADCASTPORT = 45000;
BroadcastKey::BroadcastKey(QObject *parent) : QObject(parent)
{
    updateAddresses();
    broadcastTimer.setInterval(BROADCASTINTERVAL);
    connect(&broadcastTimer, SIGNAL(timeout()), this, SLOT(sendBroadcastDatagram()));
}

void BroadcastKey::startBroadcasting()
{
    broadcastTimer.start();
}

void BroadcastKey::updateAddresses()
{
    broadcastAddresses.clear();

    foreach (QNetworkInterface interface, QNetworkInterface::allInterfaces()) {
        foreach (QNetworkAddressEntry entry, interface.addressEntries()) {
            QHostAddress broadcastAddress = entry.broadcast();
            if (broadcastAddress != QHostAddress::Null && entry.ip() != QHostAddress::LocalHost) {
                broadcastAddresses << broadcastAddress;

            }
        }
    }
}

void BroadcastKey::sendBroadcastDatagram()
{
    QByteArray datagram("#*");
    datagram.append(readFile());


    bool validBroadcastAddresses = true;
    foreach (QHostAddress address, broadcastAddresses) {
        if (broadcastSocket.writeDatagram(datagram, address, BROADCASTPORT) == -1)
            validBroadcastAddresses = false;
        else {
            qInfo() << "#broadcast: "  << datagram;
            emit reportedMessage(datagram);
        }
    }

    if (!validBroadcastAddresses)
        updateAddresses();
}

QByteArray BroadcastKey::readFile()
{

#ifdef Q_OS_WIN
#endif
    QFile file(QCoreApplication::applicationDirPath() + "/awfan.cn.config");


    file.open(QIODevice::ReadOnly);

    return file.readAll();

}

